package com.oocl.chat.controller;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import com.oocl.chat.operate.impl.ReceiveOperateImpl;
import com.oocl.chat.pojo.Message;
import com.oocl.chat.ui.LoginFrame;
import com.oocl.chat.util.Constans;
import com.oocl.thread.SendThread;

public class Client {
	public static Client client;
	private Socket socket;
	private ObjectOutputStream oos;
	private ObjectInputStream ois;
	private LoginFrame loginFrame;
	ReceiveOperateImpl roim = new ReceiveOperateImpl();
	
	
	public void start(){
		try {
			socket = new Socket("127.0.0.1",Constans.PORT);
			loginFrame = new LoginFrame();
			oos = new ObjectOutputStream(socket.getOutputStream());
			ois = new ObjectInputStream(socket.getInputStream());
			receiveMessage();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	public void receiveMessage(){
		Message message = new Message();
		boolean flag = true;
		while(flag){
			try {
				if ((message = (Message) ois.readObject()) != null) {
					receiveOperate(message);
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				System.out.println("已断开客户机");
				flag=false;
			}
		}
	}
	
	private void receiveOperate(Message message){
		int type = message.getType();
		switch(type){
		case 0:
			roim.receiveChat(message);
			break;
		case 1:
			roim.receiveShake(message);
			break;
		case 2:
			roim.receiveOnline(message);
			break;
		case 3:
			roim.receiveDownline(message);
			break;
		case 4:
			loginFrame.setVisible(false);
			roim.receiveNotifyList(message);
			break;
		}
	}
	public void sendChat(Message message){
		try {
			new Thread(new SendThread(oos, message)).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void sendShake(Message message){
		try {
			new Thread(new SendThread(oos, message)).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void sendLogin(Message message){
		try {
			new Thread(new SendThread(oos, message)).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void sendLogout(Message message){
		try {
			new Thread(new SendThread(oos, message)).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		client = new Client();
		client.start();
	}
}
